package main;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.List;


import main.parse.IPAInfo;
import main.parse.IPAReader;
import main.tools.FileTools;
import main.net.dongliu.apk.parser.ApkFile;
import main.net.dongliu.apk.parser.bean.ApkV2Signer;
import main.net.dongliu.apk.parser.bean.ApkMeta;
import main.net.dongliu.apk.parser.bean.IconFace;

/**
 * @Description:
 * @Author: MenChao
 * @Date: 2018/12/10 10:41
 */
@WebServlet(name = "appupload",urlPatterns = {"/appupload","/appupload/"})
@MultipartConfig
public class appupload extends HttpServlet {

    private  final  String  serverAddress = "https://10.49.33.241:8443";

    private  String  hostAddress = null;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("request url: " +  request.getRequestURI());
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.write("hello app main.parse");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");

            System.out.println(request.getRequestURI());
            String mainFilePath = this.getServletContext().getRealPath("/WEB-INF/AppFile");
            FileTools.createFloder(mainFilePath);
            System.out.println("主路径" + mainFilePath);
            String fileName = request.getParameter("fileName"); //ss=>xx
            String fileSize = request.getParameter("fileSize"); //ss=>xx
            System.out.println("mainFilePath :" + mainFilePath);
            System.out.println("request fileName: " + fileName + ", fileSize: "+fileSize);

            Part part = request.getPart("file");
            if (part!=null) {
                InputStream fileStream = part.getInputStream();
                FileTools.writeFile(mainFilePath,fileName,fileStream);

                String scheme =  request.getScheme();
                String  serverName = request.getServerName();
                int serverPort = request.getServerPort();
                System.out.println("scheme: " + scheme + ",serverName:" + serverName +",serverPort: " +serverPort);

                String appFullPath =  mainFilePath +"/" + fileName;

                String serverHost = scheme + "://" + serverName +":" + serverPort;

                String  ipa = this.parseIPA(appFullPath,fileName);
                if (ipa!=null){
                    this.responseText(ipa,response);

                }else{
                    String apk = this.parseAPK(serverHost,appFullPath,fileName);
                    if (apk!=null){
                        this.responseText(apk,response);
                    }else{
                        this.responseText("{\"error\":\"解析失败，不是苹果应用或安卓应用\"}",response);

                    }
                }
            }
        }catch (Exception ee){
            System.out.println(ee.getMessage());
            ee.printStackTrace();
            this.responseText("{\"error\":\"上传出错\"}",response);
        }
    }

    private  void responseText(String respnseText,  HttpServletResponse response) throws  IOException{
        response.setContentType("text/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.write(respnseText);
        pw.close();
    }


    private String parseAPK(String  serverHost,  String apkPath,String fileName){

        String jsonStr = null;
        String appName = null;
        String version = null;
        String buildNumber = null;
        String bundleIdentifier = null;

        try {
            ApkFile apkFile = new ApkFile(new File(apkPath));
            if (apkFile != null) {
                ApkMeta apkMeta = apkFile.getApkMeta();
                appName = apkMeta.getLabel();
                version = apkMeta.getVersionName();
                buildNumber = String.valueOf(apkMeta.getVersionCode());
                bundleIdentifier = apkMeta.getPackageName();


                String mainFilePath = this.getServletContext().getRealPath("/WEB-INF/AppFile");
                String  iconUrl = "" ;

                //获取icon
                List<main.net.dongliu.apk.parser.bean.IconFace>  iconList =   apkFile.getAllIcons();

                if (iconList.size() >0){//取最大图像
                    IconFace face = iconList.get(iconList.size()-1);
                    String iconExtName = FileTools.getFileExt(face.getPath());
                    String fileNamePart = FileTools.getNamePart(fileName);
                    String fileFullName =  fileNamePart + "." + iconExtName;
                    FileTools.writeFileWithByte(mainFilePath,fileFullName,face.getData());
                    iconUrl = serverHost + "/filedownload/"  + fileFullName;
                }

                String  downloadPath = serverHost +"/filedownload?fileName=" + fileName;
                System.out.println(appName);
                System.out.println(bundleIdentifier);
                System.out.println(buildNumber);
                System.out.println(version);
                jsonStr = "{\"appName\":\"" +           appName            + "\"," +
                        "\"version\":\"" +           version            + "\"," +
                        "\"buildNumber\":\"" +       buildNumber        + "\"," +
                        "\"bundleIdentifier\":\"" +  bundleIdentifier   + "\"," +
                        "\"teamName\":\"" +          "no"           + "\","  +
                        "\"appType\":\"" +          "2"           + "\","  +
                        "\"iconUrl\":\"" +         iconUrl         + "\","  +
                        "\"fileUrl\":\"" +          downloadPath          + "\""  +
                        "}";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonStr;
    }




    private  String parseIPA(String ipaPath,String fileName) {
        String jsonStr = null;
        String appName = null;
        String version = null;
        String buildNumber = null;
        String bundleIdentifier = null;
        String teamName = null;
        IPAReader reader = new IPAReader(ipaPath);
        try {
            IPAInfo info = reader.parse();
            if (info != null){//解析 ，可以添加其它信息，下面只列举了一部分
                appName = info.getAppName();
                version = info.getBundleVersionString();
                buildNumber = info.getBuildNumber();
                bundleIdentifier = info.getBundleIdentifier();
                teamName = info.getTeamName();
                System.out.println("appName: "+appName+",version: " +version+",buildNumber: " +buildNumber
                          +",bundleIdentifier: "+bundleIdentifier+",teamName: "+teamName);

                String ipaDownloadUrl = serverAddress + "/filedownload/" + fileName;
                String plist = this.getPlistFileString(ipaDownloadUrl, bundleIdentifier, version);
                //创建对应的plist
                String plistName = this.createPlistFile(fileName, plist);

                String   plistDownloadUrl = serverAddress + "/filedownload/"  + plistName+ ".plist";

                jsonStr = "{\"appName\":\"" + appName + "\"," +
                        "\"version\":\"" + version + "\"," +
                        "\"buildNumber\":\"" + buildNumber + "\"," +
                        "\"bundleIdentifier\":\"" + bundleIdentifier + "\"," +
                        "\"teamName\":\"" + teamName + "\"," +
                        "\"plistPath\":\"" + plistDownloadUrl + "\"," +
                        "\"appType\":\"" + "1" + "\"" +
                        "}";
                System.out.println(jsonStr);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  jsonStr;
    }

        //获取plist
    private  String getPlistFileString(String ipaPath,String bundleID,String version){
        String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
                "<plist version=\"1.0\">\n" +
                "<dict>\n" +
                "<key>items</key>\n" +
                "<array>\n" +
                "<dict>\n" +
                "<key>assets</key>\n" +
                "<array>\n" +
                "<dict>\n" +
                "<key>kind</key>\n" +
                "<string>software-package</string>\n" +
                "<key>url</key>\n" +
                "<string>" + ipaPath + "</string>\n" +
                "</dict>\n" +
                "<dict>\n" +
                "<key>kind</key>\n" +
                "<string>display-image</string>\n" +
                "<key>url</key>\n" +
                "<string>https://10.49.33.241:8443/static/image/120X120.png</string>\n" +
                "</dict>\n" +
                "<dict>\n" +
                "<key>kind</key>\n" +
                "<string>full-size-image</string>\n" +
                "<key>url</key>\n" +
                "<string>https://10.49.33.241:8443/static/image/180X180.png</string>\n" +
                "</dict>\n" +
                "</array>\n" +
                "<key>metadata</key>\n" +
                "<dict>\n" +
                "<key>bundle-identifier</key>\n" +
                "<string>" + bundleID + "</string>\n" +
                "<key>bundle-version</key>\n" +
                "<string>" + version + "</string>\n" +
                "<key>kind</key>\n" +
                "<string>software</string>\n" +
                "<key>title</key>\n" +
                "<string>CedarFinancialPlanner</string>\n" +
                "</dict>\n" +
                "</dict>\n" +
                "</array>\n" +
                "</dict>\n" +
                "</plist>";
        return str;
        }


    private  String  createPlistFile(String fileName,String plist) throws  IOException{
            //解析成功，创建对应的plist
        String currentFilePath = this.getServletContext().getRealPath("/WEB-INF/AppFile");

        String plistFileName = fileName.substring(0, fileName.lastIndexOf("."));

        String plistFullPath = currentFilePath + "/" + plistFileName + ".plist";
        System.out.println("plist: " + plistFullPath);
        File file = new File(plistFullPath);
        if (!file.exists()) {
            file.createNewFile();
        }
        try {
            FileOutputStream output = new FileOutputStream(file);
            OutputStreamWriter writer;
            writer = new OutputStreamWriter(output, "UTF-8");
            writer.write(plist);
            writer.close();
            output.close();
        } catch (Exception e) {
            System.err.println("========== 创建plist文件异常：" + e.getMessage());
        }
        System.out.println("========== 成功创建plist文件");
        return plistFileName;
    }

    /**
     * 文件存储主路径
     */
    private String getMainPath(){
        return  this.getServletContext().getRealPath("/WEB-INF/AppFile");
    }


}
